﻿using Kingdee.BOS;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Kingdee.K3.FIN.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
//using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;

namespace RK.FormPlugin.BPW
{
    [Description("BPW:采购情况检查，采购情况检查记录"), HotUpdate]
    public class DzPurCheckQtyDate : AbstractDynamicFormPlugIn
    {
        //取消关闭时提示是否保存
        public override void BeforeClosed(BeforeClosedEventArgs e)
        {
            base.BeforeClosed(e);
            this.Model.DataChanged = false;
        }
        
        /// <summary>
        /// 新增时，加载数据
        /// </summary>
        /// <param name="e"></param>
        public override void AfterCreateModelData(EventArgs e)
        {
            base.AfterCreateModelData(e);
            //删除空行
            var entityRows = this.Model.GetEntryRowCount("FEntity");
            for (int i = entityRows - 1; i >= 0; i--)
            {
                this.Model.DeleteEntryRow("FEntity", i);
            }
            var dataList = GetData();
            if (dataList.Rows.Count > 0)
            {
                BatchCreateRows(this.Model, dataList.Rows);
            }
        }
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            var newObj = this.Model.DataObject.Clone() as DynamicObject;
            var entity = Model.BillBusinessInfo.GetEntity("FEntity");
            var rowData = Model.GetEntityDataObject(entity);
            var newRows = rowData.Where(x => Convert.ToInt32(x["F_Select"]) == 1);
            bool isOk = true;
            string errs = "";
            if (!(newRows.Count() > 0))
            {
                this.View.ShowErrMessage("没有选择任何数据！");
                return;
            }
            if (e.BarItemKey.EqualsIgnoreCase("XRIS_tbQty"))//修改数量
            {
                //bool isOk = true;
                //string errs = "";
                ModifyQty(this.Context, newRows, out isOk, out errs);
                //if (!isOk)
                //{
                //    this.View.ShowErrMessage("采购订单，修改数量不成功！", "修改数量");
                //}
                //Logger.Info("采购订单修改数量", $"采购订单修改数量:{isOk}_{errs},修改人:{this.Context.UserName}");
                DeleteNotSeleteRows(newObj, "修改数量");
                //UpModel(this.Model, e.BarItemKey);
            }
            if (e.BarItemKey.EqualsIgnoreCase("XRIS_tbDate"))//修改日期
            {
                //bool isOk = true;
                //string errs = "";
                ModifyDate(this.Context, newRows, e.BarItemKey, out isOk, out errs);
                DeleteNotSeleteRows(newObj, "修改日期");
                //Logger.Info("采购订单修改日期", $"采购订单修改日期:{isOk}_{errs},修改人:{this.Context.UserName}");
                //UpModel(this.Model, e.BarItemKey);
            }
            else if (e.BarItemKey.EqualsIgnoreCase("XRIS_tbNextMonth"))//推迟1个月交货
            {
                //bool isOk = true;
                //string errs = "";
                ModifyDate(this.Context, newRows, e.BarItemKey, out isOk, out errs);
                DeleteNotSeleteRows(newObj, "推迟1个月交货");
                //Logger.Info("采购订单推迟1个月", $"采购订单推迟1个月:{isOk}_{errs},修改人:{this.Context.UserName}");
                //UpModel(this.Model, e.BarItemKey);
            }
            if (isOk)
            {
                this.View.ShowMessage("修改成功！");
                //删除空行
                var entityRows = this.Model.GetEntryRowCount("FEntity");
                for (int i = entityRows - 1; i >= 0; i--)
                {
                    this.Model.DeleteEntryRow("FEntity", i);
                }
                var dataList = GetData();
                if (dataList.Rows.Count > 0)
                {
                    BatchCreateRows(this.Model, dataList.Rows);
                }
            }
            else
            {
                this.View.ShowErrMessage(errs);
            }
            BusinessDataServiceHelper.Save(this.Context, newObj);
            //this.View.Close();
        }

        private void DeleteNotSeleteRows(DynamicObject obj, string v)
        {
            //var rowIndexs = model.BillBusinessInfo.GetEntryCount();
            //var entity = model.BillBusinessInfo.GetEntity("FEntity");
            DynamicObjectCollection rowData = obj["FEntity"] as DynamicObjectCollection;
            for (int i = rowData.Count - 1; i >= 0; i--)
            {
                rowData[i]["F_OpNumber"] = v;
                var isSelete = Convert.ToBoolean(rowData[i]["F_Select"]);
                if (!isSelete)
                {
                    rowData.Remove(rowData[i]);
                }
            }
        }

        private void ModifyDate(Kingdee.BOS.Context context, IEnumerable<Kingdee.BOS.Orm.DataEntity.DynamicObject> newRows, string barItemKey, out bool isOk, out string errs)
        {
            errs = "";
            isOk = true;
            //创建视图
            IBillView billView = CreateBillView.CreateView(context, "PUR_PurchaseOrder");
            ((IBillViewService)billView).LoadData();
            DynamicFormViewPlugInProxy eventProxy = billView.GetService<DynamicFormViewPlugInProxy>();
            eventProxy.FireOnLoad();
            if (newRows.Count() > 0)
            {
                foreach (var row in newRows)
                {
                    string mType = "";
                    int purEid = Convert.ToInt32(row["F_PurEntryId"]);
                    int purFid = Convert.ToInt32(GetPurFid(purEid, context)[0][0]);
                    string jhDate = Convert.ToString(row["F_SlDate"]);
                    if (barItemKey.EqualsIgnoreCase("XRIS_tbDate"))
                    {
                        mType = "修改日期";
                        jhDate = Convert.ToString(row["F_SlDate"]);
                    }
                    else if (barItemKey.EqualsIgnoreCase("XRIS_tbNextMonth"))
                    {
                        mType = "推迟1个月";
                        var purDate = Convert.ToDateTime(GetPurFid(purEid, context)[0][1]);
                        var addDay = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
                        purDate = purDate.AddDays(addDay);
                        jhDate = purDate.ToString("d");
                    }
                    billView.Model.Load(purFid);
                    DynamicObjectCollection rows = billView.Model.DataObject["POOrderEntry"] as DynamicObjectCollection;
                    for (int i = 0; i < rows.Count; i++)
                    {
                        int eid = Convert.ToInt32(rows[i]["Id"]);
                        if (eid == purEid)
                        {
                            billView.Model.SetEntryCurrentRowIndex("FPOOrderEntry", i);
                            billView.Model.SetValue("FDeliveryDate", jhDate, i);
                            billView.InvokeFieldUpdateService("FDeliveryDate", i);
                        }
                    }
                    //保存单据
                    isOk = CreateBillView.OnlySaveBill(billView, OperateOption.Create(), context, out errs);
                    Logger.Info($"采购订单{mType}", $"采购订单{mType}:{isOk}_{errs},修改人:{this.Context.UserName}");
                }
            }
        }

        private List<List<object>> GetPurFid(int purEid, Context context)
        {
            string filterString = $"FPOOrderEntry_FEntryID ={purEid}";
            var fids = Api.ExecuteBillQuery(context, "PUR_PurchaseOrder", "FID,FDeliveryDate", filterString, "FID", 1);
            return fids;
        }

        private void ModifyQty(Context context, IEnumerable<DynamicObject> newRows, out bool isOk, out string errs)
        {
            errs = "";
            isOk = true;
            //创建视图
            IBillView billView = CreateBillView.CreateView(context, "PUR_PurchaseOrder");
            ((IBillViewService)billView).LoadData();
            DynamicFormViewPlugInProxy eventProxy = billView.GetService<DynamicFormViewPlugInProxy>();
            eventProxy.FireOnLoad();
            if (newRows.Count() > 0)
            {
                foreach (var row in newRows)
                {
                    int purEid = Convert.ToInt32(row["F_PurEntryId"]);
                    //decimal txPrice = GetTxPrice(purEid, context);
                    int purFid = Convert.ToInt32(GetPurFid(purEid, context)[0][0]);
                    decimal jhQty = Convert.ToDecimal(row["F_SLQTY"]);
                    billView.Model.Load(purFid);
                    DynamicObjectCollection rows = billView.Model.DataObject["POOrderEntry"] as DynamicObjectCollection;
                    for (int i = 0; i < rows.Count; i++)
                    {
                        decimal txPrice = Convert.ToDecimal(rows[i]["TaxPrice"]);
                        int eid = Convert.ToInt32(rows[i]["Id"]);
                        if (eid == purEid)
                        {
                            billView.Model.SetValue("FQty", jhQty, i);
                            billView.Model.SetEntryCurrentRowIndex("FPOOrderEntry", i);
                            billView.InvokeFieldUpdateService("FQty", i);
                            billView.Model.SetValue("FTaxPrice", txPrice, i);
                            billView.InvokeFieldUpdateService("FTaxPrice", i);
                        }
                    }
                    //保存单据
                    isOk = CreateBillView.OnlySaveBill(billView, OperateOption.Create(), context, out errs);
                    Logger.Info("采购订单修改数量", $"采购订单修改数量:{isOk}_{errs},修改人:{this.Context.UserName}");
                }
            }
        }

        private decimal GetTxPrice(int purEid, Context context)
        {
            string filterString = $"FPOOrderEntry_FEntryID ={purEid}";
            var res = Api.ExecuteBillQuery(context, "PUR_PurchaseOrder", "FTaxPrice", filterString, "FTaxPrice", 1);
            return Convert.ToDecimal(res.FirstOrDefault().FirstOrDefault());
        }

        /// <summary>
        /// 更新表体修改类型
        /// </summary>
        /// <param name="model"></param>
        /// <param name="barItemKey"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void UpModel(IDynamicFormModel model, string barItemKey)
        {
            string xgName = "";
            if (barItemKey.EqualsIgnoreCase("XRIS_tbQty"))
            {
                xgName = "修改数量";
            }
            if (barItemKey.EqualsIgnoreCase("XRIS_tbDate"))
            {
                xgName = "修改日期";
            }
            if (barItemKey.EqualsIgnoreCase("XRIS_tbNextMonth"))
            {
                xgName = "推迟1个月";
            }
            var rowCount = model.GetEntryRowCount("FEntity");
            for (var rowIndex = 0; rowIndex < rowCount; rowIndex++)
            {
                model.SetValue("F_OpNumber", xgName, rowIndex);
            }
        }

        private void BatchCreateRows(IDynamicFormModel model, DataRowCollection rows)
        {
            model.BatchCreateNewEntryRow("FEntity", rows.Count);
            for (int i = 0; i < rows.Count; i++)
            {
                string slDate = Convert.ToDateTime(rows[i]["订单交货日期"]).AddDays(30).ToString("d");
                model.SetValue("F_PurBillNo", Convert.ToString(rows[i]["采购单号"]), i);
                model.SetValue("F_PurJhDate", Convert.ToString(rows[i]["订单交货日期"]), i);
                model.SetValue("FMaterialId", Convert.ToString(rows[i]["物料编码"]), i);
                model.SetValue("FMaterialIdName", Convert.ToString(rows[i]["物料名称"]), i);
                model.SetValue("FModel", Convert.ToString(rows[i]["规格型号"]), i);
                model.SetValue("FQty", Convert.ToDecimal(rows[i]["采购数量"]), i);
                model.SetValue("F_NotInQty", Convert.ToDecimal(rows[i]["订单未交货数量"]), i);
                model.SetValue("F_SlDate", rows[i]["收料日期"] == null ? slDate : Convert.ToString(rows[i]["收料日期"]), i);
                model.SetValue("F_SlQty", rows[i]["收料数量"] == null ? 0 : Convert.ToDecimal(rows[i]["收料数量"]), i);
                model.SetValue("F_RkDate", rows[i]["入库日期"] == null ? slDate : Convert.ToString(rows[i]["入库日期"]), i);
                model.SetValue("F_RkQty", rows[i]["入库数量"] == null ? 0 : Convert.ToDecimal(rows[i]["入库数量"]), i);
                model.SetValue("F_PurEntryId", Convert.ToInt32(rows[i]["行号"]), i);
                model.SetValue("F_XRIS_Qty_83g", Convert.ToDecimal(rows[i]["待检数量"]), i);
                model.SetValue("F_BPW_Dwgnumber", Convert.ToString(rows[i]["图号"]), i);
            }
        }

        private DataTable GetData()
        {
            string sql = string.Format(@"
            SELECT T0.FBILLNO 采购单号, 
                   T10.FNUMBER 物料编码, 
                   T11.FNAME 物料名称, 
                   T11.FSPECIFICATION 规格型号, 
                   T1.FQTY 采购数量, 
                   T2.FDELIVERYDATE 订单交货日期, 
                   T3.FREMAINRECEIVEQTY 订单未交货数量,
                   CASE
                       WHEN T3.FRECEIVEQTY > 0
                       THEN T4.FDATE
                       ELSE NULL
                   END 收料日期, 
                   T3.FRECEIVEQTY 收料数量,
                   --ISNULL(T4.FACTRECEIVEQTY,0) 收料数量, 
                   CASE
                       WHEN t3.FSTOCKINQTY > 0
                       THEN T7.FDATE
                       ELSE NULL
                   END 入库日期, 
                   t3.FSTOCKINQTY 入库数量,
                   --ISNULL(T7.FREALQTY,0) 入库数量, 
                   T1.FENTRYID 行号, 
                   --ISNULL(T4.FACTRECEIVEQTY, 0) - ISNULL(T7.FREALQTY, 0) 待检数量, 
                   T3.FRECEIVEQTY - t3.FSTOCKINQTY 待检数量, 
                   T10.F_BPW_DWGNUMBER 图号
            FROM T_PUR_POORDER T0
                 JOIN T_PUR_POORDERENTRY T1 ON T1.FID = T0.FID
                 JOIN t_PUR_POENTRYDELIPLAN T2 ON T2.FENTRYID = T1.FENTRYID
                 JOIN T_PUR_POORDERENTRY_R T3 ON T3.FENTRYID = T1.FENTRYID
                 LEFT JOIN
            (
                SELECT T4.FSID, 
                       MAX(T6.FDATE) FDATE, 
                       SUM(T5.FACTRECEIVEQTY) FACTRECEIVEQTY
                FROM T_PUR_RECEIVEENTRY_LK T4
                     JOIN T_PUR_RECEIVEENTRY T5 ON T5.FENTRYID = T4.FENTRYID
                     JOIN T_PUR_Receive T6 ON T6.FID = T5.FID
                WHERE T6.FDOCUMENTSTATUS = 'C'
                      AND T6.FCANCELSTATUS = 'A'
                      AND T4.FSTABLENAME = 't_PUR_POOrderEntry'
                GROUP BY T4.FSID
            ) T4 ON T4.FSID = T1.FENTRYID
                 LEFT JOIN
            (
                SELECT T2.FSID, 
                       MAX(T0.FDATE) FDATE, 
                       SUM(T0.FREALQTY) FREALQTY
                FROM
                (
                    SELECT T7.FSID, 
                           MAX(T9.FDATE) FDATE, 
                           SUM(T8.FREALQTY) FREALQTY
                    FROM T_STK_INSTOCKENTRY_LK T7
                         JOIN T_STK_INSTOCKENTRY T8 ON T8.FENTRYID = T7.FENTRYID
                         JOIN t_STK_InStock T9 ON T9.FID = T8.FID
                    WHERE T9.FDOCUMENTSTATUS = 'C'
                          AND T9.FCANCELSTATUS = 'A'
                          AND T7.FSTABLENAME = 'T_PUR_ReceiveEntry'
                    GROUP BY T7.FSID
                ) T0
                JOIN T_PUR_RECEIVEENTRY T1 ON T1.FENTRYID = T0.FSID
                JOIN T_PUR_RECEIVEENTRY_LK T2 ON T2.FENTRYID = T1.FENTRYID
                GROUP BY T2.FSID
            ) T7 ON T7.FSID = T1.FENTRYID
                 JOIN T_BD_MATERIAL T10 ON T10.FMATERIALID = T1.FMATERIALID
                 JOIN T_BD_MATERIAL_L T11 ON T11.FMATERIALID = T10.FMATERIALID
                                             AND T11.FLOCALEID = 2052
            WHERE T0.FCLOSESTATUS = 'A'
                  AND T3.FREMAINSTOCKINQTY > 0
                  AND T0.FDOCUMENTSTATUS = 'C'
            ORDER BY T0.FDATE, 
                     T1.FSEQ");
            DataSet data = DBServiceHelper.ExecuteDataSet(Context, sql);
            DataTable dt = data.Tables[0];
            return dt;
        }
    }
}
